"""
Case Type   : 功能测试
Case Name   : 初始用户员与普通用户权限互赋予，系统管理员回收权限
Create At   : 2024-11-29
Owner       : wan005
Description :
        1.创建普通用户
        2.初始用户与普通用户proxy权限相互赋予
        3.查看普通用户是否有初始用户的proxy权限
        4.系统管理员回收用户权限
Expect      :
        1.用户创建成功
        2.授权成功
        3.普通用户拥有初始用户proxy权限
        4.权限回收成功
History     :
"""
import os
import unittest
from yat.test import macro
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class Compatibility(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.pri_sh = CommonSH('PrimaryDbBmode')
        self.user_node = Node('PrimaryDbUser')
        self.common = Common()
        self.constant = Constant()
        self.user1 = 'user_revoke_001'

    def test_revoke(self):
        text = '-----step1:创建普通用户;expect:创建成功-----'
        self.log.info(text)
        sql1 = f'create user {self.user1} password \'{macro.COMMON_PASSWD}\';'
        res1 = self.pri_sh.execut_db_sql(sql1)
        self.log.info(res1)
        self.assertEqual(res1, self.constant.CREATE_ROLE_SUCCESS_MSG,
                        f'执行失败: {text}')

        text = '----step2:初始用户与普通用户proxy权限相互赋予;expect:成功----'
        self.log.info(text)
        sql2 = f'grant proxy on {self.user_node.ssh_user} to {self.user1} ' \
               f'with grant option;' \
               f'grant proxy on {self.user1} to {self.user_node.ssh_user};'
        res2 = self.pri_sh.execut_db_sql(sql2)
        self.log.info(res2)
        self.assertEqual(2, res2.count('GRANT ROLE'), f'执行失败: {text}')

        text = '----step3:查看普通用户是否有初始用户的proxy权限;expect:成功----'
        self.log.info(text)
        sql3 = f'\\du {self.user1}'
        res3 = self.pri_sh.execut_db_sql(sql3)
        self.log.info(res3)
        self.assertTrue('Member of' in res3 and self.user_node.ssh_user in res3,
                        f'执行失败: {text}')

        text = '----step4:系统管理员回收用户权限;expect:成功----'
        self.log.info(text)
        sql4 = f'revoke proxy on {self.user_node.ssh_user} from {self.user1};' \
               f'revoke proxy on {self.user1} from {self.user_node.ssh_user};'
        res4 = self.pri_sh.execut_db_sql(sql4)
        self.log.info(res4)
        self.assertEqual(2, res4.count('REVOKE ROLE'), f'执行失败: {text}')

    def tearDown(self):
        text = '----清理环境----'
        self.log.info(text)
        sql_cle1 = f'drop user {self.user1} cascade;'
        res_cle1 = self.pri_sh.execut_db_sql(sql_cle1)
        self.log.info(res_cle1)
        self.assertEqual(self.constant.DROP_ROLE_SUCCESS_MSG, res_cle1,
                         f'执行失败: {text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')